<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option
          :label="item.tmName"
          v-for="(item, index) in AllTradeMark"
          :value="item.id"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入SPU描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图标">
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="saleAttrIdAndValueName"
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '暂无数据可选择'
        "
      >
        <el-option
          :label="item.name"
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        style="margin: 10px 0 0 0"
        type="primary"
        size="default"
        icon="Plus"
        :disabled="saleAttrIdAndValueName ? false : true"
        @click="addSaleAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #default="scope">
            <el-tag
              v-for="item in scope.row.spuSaleAttrValueList"
              :key="item.id"
              class="mx-1"
              closable
              style="margin: 0 8px"
              @close="scope.row.spuSaleAttrValueList.splice(scope.$index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              :ref="(vc: any) => (inputArr[scope.$index] = vc)"
              v-model="scope.row.saleAttrValue"
              v-if="scope.row.flag === true"
              placeholder="请你输入属性值"
              size="small"
              style="width: 100px"
              @blur="toLook(scope.row)"
            ></el-input>
            <el-button
              v-else
              size="small"
              icon="Plus"
              @click="toEdit(scope.row, scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="saleAttr.splice(scope.$index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="default"
        @click="save"
        :disabled="saleAttr.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type {
  SpuData,
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
  Trademark,
  SpuImg,
  SaleAttr,
  HasSaleAttr,
  SaleAttrValue,
} from "../../../../api/product/spu/type";
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSalAttr,
  reqAddOrUpdateSpu,
} from "../../../../api/product/spu";
import { ref, computed, nextTick } from "vue";
import { ElMessage } from "element-plus";

let saleAttrIdAndValueName = ref<string>("");

let $emit = defineEmits(["changeScene"]);
// 点击取消，去更改父组件的，场景值
// 点击取消按钮:通知父组件切换场景为1,展示有的SPU的数据
const cancel = () => {
  $emit("changeScene", { flag: 0, params: "update" });
};

let AllTradeMark = ref<Trademark[]>([]);
let imgList = ref<SpuImg[]>([]);
let saleAttr = ref<SaleAttr[]>([]);
let allSaleAttr = ref<HasSaleAttr[]>([]);
let dialogVisible = ref<boolean>(false);
let dialogImageUrl = ref<string>("");
// 存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: "",
  spuName: "",
  description: "",
  tmId: "",
  spuImageList: [],
  spuSaleAttrList: [],
});

let inputArr = ref<any>([]);

const initHasSpuData = async (spu: SpuData) => {
  SpuParams.value = spu;
  // 调用接口获取品牌数据，图片数据，销售属性数据，销售属性值数据
  let res: AllTradeMark = await reqAllTradeMark();
  // 获取某一个品牌旗下全部售卖商品的图片
  let res1: SpuHasImg = await reqSpuImageList(spu.id as number);
  // 获取已有的SPU销售属性的数据
  let res2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number);
  // 获取整个项目全部SPU的销售属性
  let res3: HasSaleAttrResponseData = await reqAllSalAttr();

  // 全部品牌的数据
  AllTradeMark.value = res.data;
  // 对应的商品图片
  imgList.value = res1.data.map((item: any) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  // 获取已有的SPU销售属性的数据
  saleAttr.value = res2.data;
  // 获取整个项目全部SPU的销售属性
  allSaleAttr.value = res3.data;
};

// 照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
// 照片墙删除文件钩子
const handleRemove = () => {};
// 照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
  if (
    file.type === "image/png" ||
    file.type === "image/jpeg" ||
    file.type === "image/gif"
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件务必小于3M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件务必PNG|JPG|GIF",
    });
    return false;
  }
};

// 计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  // 全部销售属性:颜色、版本、尺码
  // 已有的销售属性:颜色、版本
  let unSelectArr = allSaleAttr.value.filter((item: any) => {
    return saleAttr.value.every((item1: any) => {
      return item.name !== item1.saleAttrName;
    });
  });
  return unSelectArr;
});

// 添加銷售屬性的方法
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] =
    saleAttrIdAndValueName.value.split(":");
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  saleAttr.value.push(newSaleAttr);
  saleAttrIdAndValueName.value = "";
};

const toEdit = (row: SaleAttr, $index: number) => {
  row.flag = true;
  row.saleAttrValue = "";
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
// 表单元素失却焦点的事件回调
const toLook = (row: SaleAttr) => {
  // 整理收集的属性的ID与属性值的名字
  const { baseSaleAttrId, saleAttrValue } = row;
  // 整理成服务器需要的属性值形式
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  };
  // 非法情况判断
  if (saleAttrValue?.trim() === "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空的",
    });
    return;
  }
  // 判断属性值是否在数组当中存在
  let repeat = row.spuSaleAttrValueList.find((item: any) => {
    return item.saleAttrValueName === saleAttrValue;
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值重复",
    });
    return;
  }
  // 追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue);
  row.flag = false;
};

const save = async () => {
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  SpuParams.value.spuSaleAttrList = saleAttr.value;
  let res = await reqAddOrUpdateSpu(SpuParams.value);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: SpuParams.value.id ? "更新成功" : "添加成功",
    });
    $emit("changeScene", {
      flag: 0,
      params: SpuParams.value.id ? "update" : "add",
    });
  }
};
// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  Object.assign(SpuParams.value, {
    category3Id: "",
    spuName: "",
    description: "",
    tmId: "",
    spuImageList: [],
    spuSaleAttrList: [],
  });
  imgList.value = [];
  saleAttr.value = [];
  saleAttrIdAndValueName.value = "";
  SpuParams.value.category3Id = c3Id;
  let res: AllTradeMark = await reqAllTradeMark();
  let res1: HasSaleAttrResponseData = await reqAllSalAttr();
  AllTradeMark.value = res.data;
  allSaleAttr.value = res1.data;
};

defineExpose({ initHasSpuData, initAddSpu }); //对外暴露方法，供父组件使用
</script>

<style lang="scss" scoped></style>
